import { baseURL } from "@/config/index";
import store from "@/store";
const timeout = 30000;

function handleSuccess(res, options, resolve, reject) {
  if (res.data.code === 200) {
    resolve(res.data);
  } else {
    console.log("xxxxx2", res.data, options);
    if (!options.hideErrorToast) {
      uni.showToast({ title: res.data.msg || "请求失败", icon: "none" });
    }
    reject(res);
  }
}

function handleFail(err, options, reject) {
  console.log("xxxxx", err);
  if (!options.hideErrorToast) {
    uni.showToast({
      title: err.msg || err.message || "请求失败",
      icon: "none",
    });
  }
  reject(err);
}

export const request = (method, url, data, options = {}) => {
  return new Promise((resolve, reject) => {
    uni.request({
      url: url.startsWith("http") ? url : baseURL + url,
      method,
      data: {
        openid: store.state.openid,
				unionid: store.state.unionid,
        ...data,
      },
      header: options.headers,
      timeout: options.timeout || timeout,
      success: (res) => {
        handleSuccess(res, options, resolve, reject);
      },
      fail: (err) => {
        handleFail(err, options, reject);
      },
    });
  });
};

request.post = (...params) => request("POST", ...params);
request.get = (...params) => request("GET", ...params);
